#!/usr/bin/env python3
import os
import sys
import time
from collections import Counter

from scapy.all import sniff
from scapy.layers.inet import IP, TCP

def get_if():
    ifaces = [i for i in os.listdir('/sys/class/net/') if 'eth' in i]
    if not ifaces:
        print("Cannot find any eth interface")
        exit(1)
    return ifaces[0]

class PacketCounter:
    def __init__(self):
        self.count = 0
        self.start_time = time.time()

    def handle_pkt(self, pkt):
        self.count += 1
        if IP in pkt and TCP in pkt:
            src_ip = pkt[IP].src
            dst_ip = pkt[IP].dst
            sport = pkt[TCP].sport
            dport = pkt[TCP].dport

            if self.count <= 10:  # Show details for first 10 packets
                print(f"Packet {self.count}:")
                print(f"  {src_ip}:{sport} -> {dst_ip}:{dport}")
                if hasattr(pkt[TCP], 'load') and pkt[TCP].load:
                    print(f"  Data: {pkt[TCP].load[:50]}...")
                print()

            if self.count % 10 == 0:
                elapsed = time.time() - self.start_time
                print(f"Received {self.count} packets in {elapsed:.2f} seconds")

        sys.stdout.flush()

def main():
    iface = get_if()
    counter = PacketCounter()

    print(f"Sniffing on interface {iface}")
    print("Filtering for TCP packets...")
    sys.stdout.flush()

    try:
        sniff(filter="tcp", iface=iface, prn=counter.handle_pkt)
    except KeyboardInterrupt:
        print(f"\nTotal packets received: {counter.count}")
        elapsed = time.time() - counter.start_time
        print(f"Capture duration: {elapsed:.2f} seconds")
        if elapsed > 0:
            print(f"Packet rate: {counter.count/elapsed:.2f} packets/second")

if __name__ == '__main__':
    main()
